package dao;

import bean.Express;

import java.util.HashMap;
import java.util.Random;

public class ExpressDao {
    static Random random = new Random();
    static HashMap<String , Express> map = new HashMap<>();
    static HashMap<String, String> map1 = new HashMap<>();

    /**
     * 快递的录入
     */
    public static boolean add(String number, Express express){
        if(map.containsKey(number)){
            return false;
        }
        map.put(number,express);
        //设置快递单号
        express.setNumber(number);
        //设置取件码
        String code = randomCode();
        express.setCode(code);
        map1.put(code,number);
        //设置快递的位置
        int position = randomPosition(number);
        express.setPosition(position);
        return true;
    }
    /**
     * 通过快递单号查询快递是否存在
     */
    public static boolean findByNumber(String number){
        if(map.containsKey(number)){
            return true;
        }
        return false;
    }
    /**
     * 通过取件码查询快递是否存在
     */
    public static boolean findByCode(String code){
        if(map1.containsKey(code)){
            return true;
        }
        return false;
    }
    /**
     * 修改快递的信息
     */
    public static boolean update(String number,Express newExpress){
        if(findByNumber(number)){
            Express oldExpress = map.get(number);
            newExpress.setCode(oldExpress.getCode());
            newExpress.setPosition(oldExpress.getPosition());
            map.remove(number,oldExpress);
            map.put(newExpress.getNumber(),newExpress);
            return true;
        }
        return false;
    }
    /**
     * 删除快递的信息
     */
    public static boolean delete(String number){
        if(findByNumber(number)){
            map.remove(number);
            return true;
        }
        return false;
    }
    public static boolean deleteCode(String code){
        boolean byCode = findByCode(code);
        if(byCode){
            map.remove(map1.get(code));
            map1.remove(code);
            return true;
        }
        return false;
    }
    /**
     * 生成随机取件码
     */
    public static String randomCode(){
        while (true) {
            int code1 = random.nextInt(900000) + 100000;
            String code = Integer.toString(code1);
            if(!map1.containsKey(code)){
                return code;
            }
        }
    }
    /**
     * 生成随机柜子的位置
     */
    public static int randomPosition(String number){
        Express express = map.get(number);
        while (true) {
            int position = random.nextInt(199) + 1;
            if(position != express.getPosition()){
                return position;
            }
        }
    }
    /**
     * 打印
     */
    public static HashMap<String, Express> print(){
        return map;
    }
}
